/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "GUIProcess.h"

#include <D3D11.h>

#include "../Components/GUIComponent.h"
#include "../Components/GUITexture.h"
#include "../Components/GUIButton.h"
//#include "../Components/GUIToggle.h"

#include "../Content/Texture.h"
#include "../Content/Technique.h"
#include "../Content/VertexShader.h"
#include "../Content/GeometryShader.h"
#include "../Content/PixelShader.h"

#include "../Content/RasterizerState.h"
#include "../Content/BlendState.h"
#include "../Content/SamplerState.h"
#include "../Content/DepthStencilState.h"

#include "../HLSLCPPDeclarations/GUITransform.fx"

#include "../Managers/DX11Manager.h"
#include "../Directors/DX11Director.h"


namespace Hogshead
{
	namespace DX11Rendering
	{
		ProcessCPP(Hogshead::DX11Rendering::GUIProcess)

		GUIProcess::GUIProcess(void)
		{
			_prev_vertex_shader = NULL;
			_prev_pixel_shader = NULL;
			_prev_geometry_shader = NULL;

			_prev_rasterizer_state = NULL;
			_prev_blend_state = NULL;
			_prev_sampler_state = NULL;

			_gui_transform_buffer = NULL;
		}

		GUIProcess::~GUIProcess(void)
		{
			if(_gui_transform_buffer)
				_gui_transform_buffer->Release();
		}

		void GUIProcess::initialize()
		{
			_prev_vertex_shader = NULL;
			_prev_pixel_shader = NULL;
			_prev_geometry_shader = NULL;

			_prev_rasterizer_state = NULL;
			_prev_blend_state = NULL;
			_prev_sampler_state = NULL;

			DX11Manager::createConstantBuffer(sizeof(GUITransform2D), &_gui_transform_buffer);

			this->_enabled = true;
		}

		void GUIProcess::registerComponent(IComponent* in_component)
		{
			if(in_component->is<GUITexture>() || in_component->is<GUIButton>())
			{
				_registered_components.add(in_component);
			}
		}

		void GUIProcess::render(Camera* in_active_camera, HashSet<void*>* in_nonculling_components)
		{
			//clear out all our knowledge about the state of things on the card
			_prev_vertex_shader = NULL;
			_prev_pixel_shader = NULL;
			_prev_geometry_shader = NULL;

			_prev_rasterizer_state = NULL;
			_prev_blend_state = NULL;
			_prev_sampler_state = NULL;
			_prev_depth_stencil_state = NULL;

			//setup the viewport
			D3D11_VIEWPORT viewport;
			viewport.Width = (FLOAT)DX11Manager::getWidth();
			viewport.Height = (FLOAT)DX11Manager::getHeight();
			viewport.MinDepth = 0.0f;
			viewport.MaxDepth = 1.0f;
			viewport.TopLeftX = 0;
			viewport.TopLeftY = 0;
			DX11Manager::setViewport( &viewport );

			GUIComponent* guiObject;
			for(int i = 0; i < _registered_components.size(); i++)
			{
				if(!_registered_components[i]->isActive())
					continue;

				if(_registered_components[i]->is<GUITexture>())
					guiObject = _registered_components[i]->as<GUITexture>();
				else if(_registered_components[i]->is<GUIButton>())
					guiObject = _registered_components[i]->as<GUIButton>();

				const Technique* current_draw_tech = guiObject->technique();

				for(int j = 0; j < current_draw_tech->passes().size(); j++)
				{
					Pass* current_pass = current_draw_tech->passes()[j];

					if(!_prev_vertex_shader || current_pass->_vs != _prev_vertex_shader)
					{
						DX11Manager::setInputLayout(current_pass->_vs->_input_layout);
						DX11Manager::setVertexShader(current_pass->_vs->_vs);
						_prev_vertex_shader = current_pass->_vs;
					}
					if(!_prev_geometry_shader || current_pass->_gs != _prev_geometry_shader)
					{
						if(current_pass->_gs)
						{
							DX11Manager::setGeomentryShader(current_pass->_gs->_gs);
							_prev_geometry_shader = current_pass->_gs;
						}
						else
						{
							DX11Manager::setGeomentryShader(NULL);
							_prev_geometry_shader = NULL;
						}
					}
					if(!_prev_pixel_shader || current_pass->_ps != _prev_pixel_shader)
					{
						DX11Manager::setPixelShader(current_pass->_ps->_ps);
						_prev_pixel_shader = current_pass->_ps;
					}


					//get the gui object's position and extents
					Vector2 guiObjectPosition = guiObject->component_position() + guiObject->_parent_panel->getTransform2D().getWorldTranslation();
					Vector2 guiObjectExtents = guiObject->component_extents();
					//put both position and extents into texcoord space (-1 to 1)
					_gui_transform._position = Vector2(((guiObjectPosition.x / DX11Manager::getWidth()) * 2.0f) - 1.0f, ((guiObjectPosition.y / DX11Manager::getHeight()) * 2.0f) - 1.0f);
					_gui_transform._extents = Vector2((guiObjectExtents.x / DX11Manager::getWidth()) * 2.0f, (guiObjectExtents.y / DX11Manager::getHeight()) * 2.0f);					
					_gui_transform._rotation = guiObject->_parent_panel->getTransform2D().getWorldOrientation();
					//bind the constant buffer for the transform
					DX11Manager::bindConstantBuffer(&_gui_transform_buffer, 0, (ShaderBindFlags) (VERTEX_SHADER | GEOMETRY_SHADER));
					DX11Manager::updateConstantBuffer(_gui_transform_buffer, &_gui_transform);



					for(int j = 0; j < guiObject->constantBufferGroup().size(); j++)
					{
						DX11Manager::bindConstantBuffer(guiObject->constantBufferGroup().get(j).buffer(),
							guiObject->constantBufferGroup().get(j).registerNumber(),
							guiObject->constantBufferGroup().get(j).shaderBindFlags());
					}


					if(!_prev_rasterizer_state || current_pass->_rasterizer_state != _prev_rasterizer_state )
					{
						_prev_rasterizer_state = current_pass->_rasterizer_state;
						DX11Manager::setRasterizerState(_prev_rasterizer_state->_rasterizer_state);
					}

					if(!_prev_blend_state || current_pass->_blend_state != _prev_blend_state)
					{
						_prev_blend_state = current_pass->_blend_state;
						DX11Manager::setBlendState(_prev_blend_state->_blend_state, NULL, 0xffffffff);
					}

					if(!_prev_depth_stencil_state || current_pass->_depth_stencil_state != _prev_depth_stencil_state)
					{
						_prev_depth_stencil_state = current_pass->_depth_stencil_state;
						DX11Manager::setDepthStencilState(_prev_depth_stencil_state->_depth_stencil_state);
					}

					for( int j = 0; j < current_pass->_sampler_states.size(); j++ )
						DX11Manager::setSamplers(j, 1, &current_pass->_sampler_states[j]->_sampler_state, current_pass->_sampler_states[j]->shader_flags);

					DX11Manager::setPSShaderResource(0, &guiObject->texture()->_shader_resource_view);

					DX11Manager::setVertexBuffer(guiObject->vertex_buffer(), sizeof(GUIVertex));

					DX11Manager::draw(4, 0);
				}
			}
		}
		
		void GUIProcess::finalize()
		{
			_registered_components.clear();

			_prev_vertex_shader = NULL;
			_prev_pixel_shader = NULL;
			_prev_geometry_shader = NULL;

			_prev_rasterizer_state = NULL;
			_prev_blend_state = NULL;
			_prev_sampler_state = NULL;

			//ZeroMemory(&_gui_transform_buffer, sizeof(GUITransform2D));
			ZeroMemory(&_gui_transform, sizeof(GUITransform2D));

			if(_gui_transform_buffer)
			{
				_gui_transform_buffer->Release();
				_gui_transform_buffer = NULL;
			}
		}
	}
}